<template>
	<view class="box">
		<u--form class="form" :model="form" ref="form">

			<u-form-item label="任务类型:" :labelWidth="90" prop="form.urgent">
				<u-radio-group v-model="form.urgent">
					<u-radio :customStyle="{marginLeft: '8px'}" v-for="(item, index) in taskType" :key="index"
						:label="item.name" :name="item.id" @change="radioChange">
					</u-radio>
				</u-radio-group>
			</u-form-item>


			<u-form-item label="任务等级:" :labelWidth="90" prop="form.grade">
				<u-picker :show="gradeShow" :columns="grades" @confirm="selectTaskGrade"
					@close="this.gradeShow = false"></u-picker>
				<text @click="this.gradeShow = true">{{gradeName}}</text>
			</u-form-item>


			<u-form-item label="证书类型" :labelWidth="90" v-if="form.grade === 'a'">
				<!-- 选择证书类型 -->
				<u-checkbox-group v-model="form.actCertify" @change="selectCertify" placement="column">
					<u-checkbox :customStyle="{marginBottom: '8px',margin :'3px'}" v-for="(item, index) in types"
						:key="item.id" :label="item.name" :name="item.id">
					</u-checkbox>
				</u-checkbox-group>
			</u-form-item>

			<u-form-item label="特长类型" :labelWidth="90">
				<!-- 特长类型 -->
				<u-checkbox-group v-model="form.actSpecialType" @change="selectSpecial" placement="column">
					<u-checkbox :customStyle="{marginBottom: '8px'}" v-for="(item, index) in specialTypeList"
						:key="item.id" :label="item.name" :name="item.id">
					</u-checkbox>
				</u-checkbox-group>
			</u-form-item>

			<u-form-item label="任务标题:" :labelWidth="90" prop="form.title" :required="true">
				<u--input placeholder="请输入任务标题" border="surround" v-model="form.title"></u--input>
			</u-form-item>
			<u-form-item label="任务人数:" :labelWidth="90" prop="form.userNum" :required="true">
				<u-number-box v-model="form.userNum"></u-number-box>
			</u-form-item>

			<u-form-item label="开始时间" :labelWidth="90" prop="form.startTime" :required="true">
				<view class="" @click="this.startDateShow = true">
					{{form.startTime === '' ? '请选择开始时间':form.startTime}}
				</view>
				<u-datetime-picker ref="datetimePicker" :formatter="formatter" @confirm="confirmStartDate"
					:show="startDateShow" :minDate="Date.now()" mode="datetime">
				</u-datetime-picker>

				<u-datetime-picker ref="datetimePicker" :formatter="formatter" @confirm="confirmEndDate"
					:show="endDateTimeShow" :minDate="minDate" mode="datetime">
				</u-datetime-picker>
			</u-form-item>

			<u-form-item label="结束时间:" :labelWidth="90" prop="form.endTime" :required="true">
				<view class="" @click="this.endDateTimeShow = true">
					{{form.endTime === '' ? '请选择结束时间':form.endTime}}
				</view>
			</u-form-item>

			<u-form-item label="任务地址:" :labelWidth="90" prop="form.address" :required="true">
				<u--input placeholder="请输入任务地址" border="surround" 
        v-model="form.address"></u--input>
			</u-form-item>
      <u-row>
        <!-- offset="8" -->
      	<u-col :span="4" offset="3">
      		<u-button type="success" text="一键选择地址" @click="chooseAddress"></u-button>
      	</u-col>
      </u-row>
      
			<u-form-item label="任务内容:" :labelWidth="90" prop="form.detail">
				<u--textarea v-model="form.detail" count autoHeight placeholder="请输入内容"></u--textarea>
			</u-form-item>

			<u-form-item label="任务图片:" :labelWidth="90" prop="form.detail">
				<u-upload @afterRead="afterRead" :previewFullImage="true" name="task" :maxCount="1" width="250"
					height="150" uploadText="任务相关图片">
					<image :src="form.imageSrc=== ''? '':form.imageSrc" mode="widthFix"
						style="width: 250px;height: 150px;"></image>
				</u-upload>
			</u-form-item>
			<view class="resource">
				<!-- 添加物质 -->
				<view class="selectResource-btn" @click="addResource" v-if=" form.resourceList.length === 0">
					添加物质
				</view>

				<view class="selectResource-box" v-else>
					<view class="selectResource-box-top">
						<u-row>
							<u-col customStyle="text-align: center;" :span="1">#</u-col>
							<u-col customStyle="text-align: center;" :span="2">类型</u-col>
							<u-col customStyle="text-align: center;" :span="2">名称</u-col>
							<u-col customStyle="text-align: center;" :span="5">数量</u-col>
							<u-col customStyle="text-align: center;" :span="2">操作</u-col>
						</u-row>
					</view>
					<view class="selectResource-item" v-for="(item,index) in form.resourceList" :key="index"
						@click="resourceActIndex = index">
						<u-picker ref="uPicker" :show="resourceShow" :columns="resources" @change="selectResourceChange"
							@confirm="selectResource" @close="this.resourceShow = false"></u-picker>
						<view style="text-align: center;" @click="this.resourceShow = true" v-if="item.name === ''">
							点击选择物质</view>
						<u-row v-else>
							<u-col customStyle="text-align: center;" :span="1">{{index+1}}</u-col>
							<u-col customStyle="text-align: center;" :span="2">{{item.category}}</u-col>
							<u-col customStyle="text-align: center;" :span="2">{{item.name}}</u-col>
							<u-col customStyle="text-align: center; padding-left: 20rpx" :span="5">
								<u-number-box v-model="item.num"></u-number-box>
							</u-col>
							<u-col customStyle="text-align: center;" :span="2"><text class="deleteBtn"
									@click="deleteResource(index)">删除</text></u-col>
						</u-row>
					</view>

					<view class="selectResource-btn" @click="addResource">
						添加物质
					</view>
				</view>
			</view>

			<!-- 推荐用户列表 -->
			<view class="recommend-user">
				<view class="title">
					推荐志愿者列表:
				</view>
				<view class="user-list-table">
					<view class="recommend-user-list-top">
						<u-row
							customStyle="padding:10rpx; color:black; font-size:16px; border-bottom: 1rpx solid #bdbfbf; height: 40rpx;">
							<u-col :span="3">
								<u-switch :size="20" v-model="selectAll" @change="selectAllRecommendUser"
									inactiveColor="#bebec1" activeColor="#00aaff"></u-switch>
							</u-col>
							<u-col :span="2">姓名</u-col>
							<u-col :span="3">电话号码</u-col>
						</u-row>
					</view>
					<u-checkbox-group placement="column" :value="form.activeUserList" @change="checkBoxChange">
						<view class="recommend-user-list" v-for="item in recommendUserList" :key="item.id">
							<u-row>
								<u-col :span="3">

									<u-checkbox :size="30" :customStyle="{marginBottom: '8px'}" :name="item.id">
									</u-checkbox>

								</u-col>
								<u-col :span="2">
									{{item.name}}
								</u-col>
								<u-col :span="3">
									{{item.phone}}
								</u-col>
							</u-row>

						</view>
					</u-checkbox-group>
				</view>

			</view>

			<!-- 指定参加任务的人员列表 -->
			<view class="designate-user-list">
				<view class="title">
					指定参加任务的志愿者列表：
				</view>
				<view class="designate-user-list-table">
					<u-row
						customStyle="padding:10rpx; color:black; font-size:16px; border-bottom: 1rpx solid #bdbfbf; height: 40rpx;">
						<u-col :span="2">编号</u-col>
						<u-col :span="3">姓名</u-col>
						<u-col :span="5">电话号码</u-col>
						<u-col :span="2">操作</u-col>
					</u-row>
					<view class="designate-user-list-table-item" v-for="(item,index) in form.designateUserList"
						:key="item.id">
						<u-row
							customStyle="padding:10rpx; color:black; font-size:16px; border-bottom: 1rpx solid #bdbfbf; height: 40rpx;">
							<u-col :span="2">{{item.id}}</u-col>
							<u-col :span="3">{{item.name}}</u-col>
							<u-col :span="5">{{item.phone}}</u-col>
							<u-col :span="2">
								<view class="delete-item" @click="deleteDesignateUser(index)">
									删除
								</view>
							</u-col>
						</u-row>
					</view>
					<view class="add-designate-user" @click="addDesignateUserShow = true">
						添加指定志愿者
					</view>
					<view class="btn">
						<view class="cancel" @click="cancel">
							取消
						</view>
						<view class="submit" @click="submit">
							发布
						</view>
					</view>
					<u-popup customStyle="padding:20rpx;" :show="addDesignateUserShow"
						@close="addDesignateUserShowClose">
						<view>
							
							<u--input customStyle="margin-bottom: 15rpx;" placeholder="请输入志愿者名称" border="surround"
								v-model="user.name"></u--input>
							<u--input customStyle="margin-bottom: 15rpx;" placeholder="请输入志愿者手机号" border="surround"
								v-model="user.phone"></u--input>
							<view class="btn">
								<view class="cancel" @click="addDesignateUserShowClose">
									取消
								</view>
								<view class="submit" @click="addDesignateUserShowsubmit">
									添加
								</view>
							</view>
						</view>
					</u-popup>
				</view>
			</view>
		</u--form>

	</view>
</template>

<script>
	export default {

		data() {
			return {
    /*    position: {
        	// 定位的具体名称
        	name: '洗面桥社区',
        	// 详细位置
        	address: '四川省成都市郫都区中心大道二段一号',
        	latitude: '29.58832234563708',
        	longitude: '106.56436432812498',
        }, */
				//任务的最小时间
				minDate: 0,
				id: 0,
				//添加的志愿者
				user: {
					name: '',
					phone: ''
				},
				//表单数据
				form: {
         /* position:{
            // 定位的具体名称
            name: '',
            // 详细位置
            address: '',
            latitude: '',
            longitude: '',
          }, */
					id: 0,
					title: '',
					grade: 'c',
					detail: '',
					startTime: '',
					endTime: '',
					userNum: 0,
					address: '',
					imageSrc: '',
					urgent: 0,
					//默认选择的志愿者 存放志愿者id
					activeUserList: [],

					//激活的证书类型列表 存放证书类型id
					actCertify: [],

					//激活的特长列表 存放证书类型id
					actSpecialType: [],

					//指定参加人员列表
					designateUserList: [],

					//物质列表
					resourceList: [],
				},
				//任务等级列表
				grades: [
					['持证人员', '持有平台证', '非持证人员']
				],
				//任务类型
				taskType: [{
					id: 0,
					name: '普通任务',
				}, {
					id: 1,
					name: '紧急任务',
				}],

				//选择的物质
				resources: [],

				//选择的物质数据
				resourcesData: [],

				//证书类型列表
				types: [],

				//特长类型列表
				specialTypeList: [],

				//推荐志愿者列表
				recommendUserList: [],

				//控制是否全选
				selectAll: false,

				//控制选择选择任务等级
				gradeShow: false,

				//控制选择的证书类型
				typeShow: false,

				//控制添加指定志愿者显示
				addDesignateUserShow: false,

				//控制选择物质显示与否
				resourceShow: false,

				//选择日期
				startDateShow: false,
				//选择时间
				endDateTimeShow: false,
				//选择的任务等级名称
				gradeName: '请选择任务等级',

				//选择的证书类型名称
				typeName: "请选择证书的类型",

				//选择物质激活的的先把
				resourceActIndex: 0,

				//
				timer: null
			};
		},
		onLoad(option) {
			console.log(option)
			//获取证书类型
			this.getCertifyTypeList();

			//获取特长类型
			this.getSpecialTypeList();

			//获取物质
			this.getResource();
			var temp = option.id
			if (temp === undefined) {

			} else {
			
				//编辑任务
				this.$request({
					url: `${this.$baseUrl}/task/edit/${option.id}`,
					method: 'GET',
				}).then(res => {

					if (res.data.status) {
						this.form = res.data.data
						this.editInit();

					}
				}).catch(res => {
					console.log(res)
				})
			}
		},
		
		
		methods: {
      //选择任务住址
      chooseAddress() {
      	// console.log(this.position)
        let that = this
      	uni.chooseLocation({
      		success: function(res) {
      			// that.position = res
         //    console.log("我选择的定位",this.position)
      			// console.log('位置名称：' + res.name);
      			// console.log('详细地址：' + res.address);
      			// console.log('纬度：' + res.latitude);
      			// console.log('经度：' + res.longitude);
            that.form.address =  res.name
            that.form.position = res
            // console.log("表单的地址定位",that.form.position)
        
      			this.covers = [{
      				latitude: res.latitude,
      				longitude: res.longitude,
      				iconPath: '../../static/images/location.png', //地图上的图标
      				width: 25, //宽
      				height: 25, //高
      				callout: { //自定义标记点上方的气泡窗口 点击有效  
      					content: res.address, //文本
      					color: '#ffffff', //文字颜色
      					fontSize: 14, //文本大小
      					borderRadius: 2, //边框圆角
      					bgColor: '#00c16f', //背景颜色
      					display: 'ALWAYS', //常显
      					padding: 5 //气泡窗口的内间距
      				},
      			}]
          
            // console.log(res.address)
            // const address = res.address
            // that.form.address =address
      		},
      		fail(res) {
      			// console.log("失败了")
      			console.log(res)
      		}
      	});
        //这里虽然在方法里面，但是执行的顺序比选择地址成功的回调函数先执行
      	console.log(this.position)
      	// this.form.homeAddress = this.position.address + this.position.name
      	// this.form.latitude = this.position.latitude
      	// this.form.longitude = this.position.longitude
      },
			
			//选择任务类型改变
			radioChange(res){
				this.form.urgent = res
			},
			
			//编辑初始化
			editInit() {
				if (this.form.grade === 'c') {
					this.gradeName = '非持证人员'
				}
				if (this.form.grade === 'b') {
					this.gradeName = '持有平台证'
				} else {
					this.gradeName = '持证人员'
				}

			},

			//时间戳转化为时间
			timestampToTime(timestamp) {
				timestamp = timestamp ? timestamp : null;
				let date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
				let Y = date.getFullYear() + '-';
				let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
				let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
				let h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
				let m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
				let s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
				return Y + M + D + h + m + s;

			},

			//格式化时间
			formatter(type, value) {
				if (type === 'year') {
					return `${value}年`
				}
				if (type === 'month') {
					return `${value}月`
				}
				if (type === 'day') {
					return `${value}日`
				}
				if (type === 'hour') {
					return `${value}时`
				}
				if (type === 'minute') {
					return `${value}分`
				}
				return value
			},

			//提交选者的开始时间
			confirmStartDate(res) {
				this.form.startTime = this.timestampToTime(res.value)
				this.minDate = res.value
				//console.log(res)
				this.startDateShow = false
			},

			//提交选者的结束时间
			confirmEndDate(res) {
				this.form.endTime = this.timestampToTime(res.value)
				this.endDateTimeShow = false
				console.log(res)
			},

			//获取物质
			getResource() {
				this.$request({
					url: `${this.$baseUrl}/resource`
				}).then(res => {
					this.resources = res.data.data[0]
					this.resourcesData = res.data.data[1]

				}).catch(res => {
					console.log(res)

				})
			},

			//获取证书类型
			getCertifyTypeList() {
				this.$request({
					url: `${this.$baseUrl}/users/certifyTypeList`
				}).then(res => {
					this.types = res.data.data
					this.resources
				}).catch(res => {
					console.log(res)

				})
			},

			//获取特长类型
			getSpecialTypeList() {
				this.$request({
					url: `${this.$baseUrl}/users/specialTypeList`
				}).then(res => {
					this.specialTypeList = res.data.data
				}).catch(res => {
					console.log(res)

				})
			},
			//获取推荐用户表单节流
			getRecommoendUserListThrottling() {

				console.log(this.timer)

				if (this.timer) {
					clearTimeout(this.timer)

				}
				this.timer = setTimeout(() => {
					this.getRecommoendUserList()
					this.timer = null

				}, 5000)


			},

			//获取推荐用户列表
			getRecommoendUserList() {

				let reUser = {
					grade: 'a',
					actCertify: [],
					actSpecialType: []
				}
				reUser.grade = this.form.grade;
				reUser.actCertify = this.form.actCertify
				reUser.actSpecialType = this.form.actSpecialType
				this.$request({
						url: `${this.$baseUrl}/tasks/recommend`,
						data: reUser,
						method: 'POST'
					})
					.then(res => {
						this.recommendUserList = res.data.data
						console.log(res)

					})
					.catch(res => {
						console.log(res)

					})
			},

			//选择证书类型
			selectCertify(res) {
				this.form.actCertify = res
				this.getRecommoendUserListThrottling()
			},

			//选择特长类型 
			selectSpecial(res) {
				this.form.actSpecialType = res
				this.getRecommoendUserListThrottling()
			},

			//选择任务等级
			selectTaskGrade(index) {
				console.log(index)
				this.gradeName = index.value[0]
				this.gradeShow = false
				this.form.grade = this.getGrade(index.indexs[0])
				this.getRecommoendUserListThrottling()
			},

			//
			getGrade(index) {
				let arr = ['a', 'b', 'c']
				return arr[index]
			},

			/* //选择的证书类型
			selectType(res) {
				this.form.typeId = res.value[0].id
				this.typeName = res.value[0].name
				this.typeShow = false
			}, */

			// 新增图片
			afterRead(even) {
				uni.uploadFile({
					url: `${this.$baseUrl}/image/upload`,
					filePath: even.file.url,
					name: 'file',
					success: (res) => {
						let json = JSON.parse(res.data)
						this.form.imageSrc = `${this.$baseUrl}/image/download?name=${json.data}`
					},
					fail: (res) => {
						console.log(res)
					}
				})
			},

			//添加物质
			addResource() {
				this.form.resourceList.push({
					id: 0,
					category: '',
					name: '',
					num: 0,
				})
			},

			//选择物质
			selectResource(res) {
				console.log(res)
				this.form.resourceList[this.resourceActIndex] = {
					id: 0,
					category: res.value[0],
					name: res.value[1],
					num: res.value[2],
				}
				this.resourceShow = false
			},

			//选择物质的类型改变
			selectResourceChange(e) {

				if (e.columnIndex === 0) {
					this.$refs.uPicker[0].setColumnValues(1, this.resourcesData[e.index])
				}
			},
			//删除物质
			deleteResource(index) {
				this.form.resourceList.splice(index, 1)
			},

			//选择全部推荐用户
			selectAllRecommendUser() {
				console.log(this.selectAll)
				if (this.selectAll) {
					this.recommendUserList.forEach(item => {
						this.form.activeUserList.push(item.id)
						console.log(this.form.activeUserList)
					})
				} else {
					this.form.activeUserList = []
				}
			},

			//复选框改变
			checkBoxChange(res) {
				this.form.activeUserList = res
				if (res.length === this.recommendUserList.length) {
					this.selectAll = true
				} else {
					this.selectAll = false
				}

			},

			//删除指定下标的 指定志愿者
			deleteDesignateUser(index) {
				this.form.designateUserList.splice(index, 1)
			},

			//关闭
			addDesignateUserShowClose() {
				this.addDesignateUserShow = false
				this.user = {
					id: '',
					name: '',
					phone: ''
				}
			},

			//添加指定志愿者
			addDesignateUserShowsubmit() {
				if (this.user.id === '' || this.user.name === '' || this.user.phone === '') {
					uni.showToast({
						title: '请完成所有输入',
						icon: 'error'
					})
				} else {
					this.form.designateUserList.push(this.user)
					this.addDesignateUserShow = false
					this.user = {
						id: '',
						name: '',
						phone: ''
					}
				}
			},

			//发布任务
			submit() {
				const id = uni.getStorageSync("admin").id
				console.log(id)

				if (this.form.title === '' || this.form.userNum === 0 || this.form.endTime === '' || this.form.startTime === '' || this.form.address === '') {
					uni.showToast({
						title: '标*的不能为空',
						icon: 'error',
						duration: 2000
					});
				} else {
					if (this.form.id === 0) {
						// 增加任务
						this.$request({
							url: `${this.$baseUrl}/addTask/${id}`,
							data: this.form,
							method: 'POST',
						}).then(res => {
							if (res.data.status) {
								uni.showToast({
									title: res.data.msg,
									icon: "success"
								})
								uni.navigateTo({
									url: `/package_admin/emergencyAdministrator/emergencyAdministrator`
								})
							} else {
								uni.showToast({
									title: res.data.mgs,
									icon: "error",
									duration: 2000
								})
							}

						}).catch(res => {
							console.log(res)
						})
					} else {
						//编辑任务
            console.log("编辑任务a")
            console.log(this.form)
						this.$request({
							url: `${this.$baseUrl}/editTask/${id}`,
							data: this.form,
							method: 'POST',
						}).then(res => {
							if (res.data.status) {
								uni.showToast({
									title: res.data.msg,
									icon: "success"
								})
								uni.navigateTo({
									url: "/package_admin/emergencyAdministrator/emergencyAdministrator"
								})
							} else {
								uni.showToast({
									title: res.data.mgs,
									icon: "error",
									duration: 2000
								})
							}
						}).catch(res => {
							console.log(res)
						})
					}
				}


			},

			//取消任务的发布
			cancel() {
				this.form = {
					id: 0,
					title: '',
					grade: 0,
					detail: '',
					startTime: '',
					endTime: '',
					userNum: 1,
					address: '',
					imageSrc: '',
					urgent: 0,
					activeUserList: [],
					designateUserList: [],
					resourceList: [],
				}

				this.activeUserList = []
				this.recommendUserList = []

				//控制是否全选
				this.selectAll = false

				//控制选择选择任务等级
				this.gradeShow = false

				//控制选择的证书类型
				this.typeShow = false

				//控制添加指定志愿者显示
				this.addDesignateUserShow = false
			}

		}
	}
</script>

<style lang="scss">
	.box {
		padding: 20rpx;

		.resource {
			border: 1rpx solid #d6d6d6;
			padding: 20rpx;

			.selectResource-btn {
				margin-top: 20rpx;
				width: 180rpx;
				height: 40rpx;
				padding: 10rpx;
				background-color: #ffaa7f;
				border-radius: 10rpx;
				text-align: center;
			}

			.selectResource-box {
				.selectResource-box-top {
					padding: 8rpx;
					border-bottom: 1rpx solid #b8acb4;
				}

				.selectResource-item {
					border-bottom: 1rpx solid #b8acb4;
					padding: 10rpx;

					.deleteBtn {
						background-color: #55aaff;
						padding: 8rpx;
						border-radius: 10rpx;
						border: 1rpx solid #ffeef9;
					}
				}
			}
		}


		.recommend-user {
			.title {
				margin-top: 20rpx;
				margin-bottom: 20rpx;
			}

			.user-list-table {
				border: 1rpx solid #D5D5D5;

				.recommend-user-list {
					margin: 20rpx;
				}
			}
		}

		.designate-user-list {
			margin-top: 20rpx;

			.title {
				font-size: 32rpx;
			}

			.designate-user-list-table {
				padding: 20rpx;
				margin-top: 10rpx;
				border: 1rpx solid #d9d9d9;

				.designate-user-list-table-item {
					.delete-item {
						border: 1rpx solid #3d7bb8;
						padding: 5rpx;
						border-radius: 10rpx;
						text-align: center;
					}
				}

				.add-designate-user {
					background-color: #3d7bb8;
					margin-top: 15rpx;
					width: 250rpx;
					height: 40rpx;
					padding: 10rpx;
					text-align: center;
				}

				.btn {
					display: flex;
					justify-content: space-around;

					.submit {
						margin-top: 15rpx;
						padding: 10rpx;
						border-radius: 10rpx;
						border: 1px solid #c78500;
						width: 100rpx;
						text-align: center;
					}

					.cancel {
						margin-top: 15rpx;
						padding: 10rpx;
						border-radius: 10rpx;
						border: 1px solid #c78500;
						width: 100rpx;
						text-align: center;
					}
				}
			}
		}
	}
</style>
